import axios from 'axios';
import { ElMessage } from 'element-plus';
import { useUserInfo } from '/@/stores/userInfo';
import { Session } from '/@/utils/storage';
import { storeToRefs } from 'pinia';
import { useErrorInfo } from '/@/stores/errorInfo';
import { UserInfosState } from '/@/stores/interface';
import { NextLoading } from '/@/utils/loading';
// 配置新建一个 axios 实例
const service = axios.create({
	baseURL: import.meta.env.VITE_API_URL as any,
	timeout: 50000,
	headers: { 'Content-Type': 'application/json; charset=UTF-8' },
});
let loadingNum = 0;
// 添加请求拦截器
service.interceptors.request.use(
	(config) => {
		// 在发送请求之前做些什么 token
		if (Session.get('token')) {
			(<any>config.headers).common['Authorization'] = `${Session.get('token')}`;
			(<any>config.headers).common['Token'] = `${Session.get('token')}`;
		}
		// loadingNum++;
		// NextLoading.start();
		let data;
		config.data && typeof config.data === 'string' ? (data = JSON.parse(config.data)) : (data = config.data);
		data && data.ddesa ? (config.headers['dde-sa'] = data.ddesa) : config.headers['dde-sa'] ? delete config.headers['dde-sa'] : '';
		if (config.method === 'post') {
			if (config.data === null || config.data === 'null') {
				delete config.data;
			}
		}

		return config;
	},
	(error) => {
		// 对请求错误做些什么
		console.log('service.interceptors.request: ', error);
		return Promise.reject(error);
	}
);

// 添加响应拦截器
service.interceptors.response.use(
	(response) => {
		// 对响应数据做点什么
		console.log('responseresponse', response, loadingNum);
		// loadingNum--;
		// if (loadingNum === 0) {
		// 	setTimeout(() => {
		// 		NextLoading.done();
		// 	}, 500);
		// }
		const res = response.data;
		const storesErrorInfo = useErrorInfo();
		const { errorInfo } = storeToRefs(storesErrorInfo);
		if (res.code === '9998' || res.code === '1021') {
			ElMessage({
				message: '登录超时，请重新登录!',
				type: 'error',
				duration: BASE_API.MSG_SHOW_TIME,
			});
			Session.clear();
			const storeuser = useUserInfo();
			storeuser.setUserInfos({} as UserInfosState);
			window.location.href = '/'; // 去登录页

			return Promise.reject(service.interceptors.response);
		} else {
			let msg = '操作出错，请稍侯再试';
			if (res.code === undefined || res.code === null || res.code === '' || res.code !== '0000') {
				if (res.code === 0) {
					return response.data;
				}
				msg = errorInfo.value.get(res.code) as string;
				if (msg === undefined || msg === null || msg === '') {
					msg = '操作出错，请稍侯再试';
				}
				if (res.code !== undefined && res.code !== null) {
					msg = res.code + '-' + msg;
				}

				ElMessage({
					message: msg,
					type: 'error',
					duration: BASE_API.MSG_SHOW_TIME,
				});
				return Promise.reject('error');
			}
		}
		return handleResponse(res);
	},
	(error) => {
		console.log(error);
		if (error.request.status === 401) {
			ElMessage({
				message: '登录超时，请重新登录!',
				type: 'error',
				duration: BASE_API.MSG_SHOW_TIME,
			});
			Session.clear();
			localStorage.clear();
			const storeuser = useUserInfo();
			storeuser.setUserInfos({} as UserInfosState);
			window.location.href = '/'; // 去登录页
			return Promise.reject(service.interceptors.response);
		}
		if (error.request.status === 404) {
			ElMessage({
				message: '没有找到服务',
				type: 'error',
				duration: BASE_API.MSG_SHOW_TIME,
			});
			// 退回到上一个页面。或者跳转到404页面
			// const router = useRouter();
			// router.go(-1);
		} else {
			const storesErrorInfo = useErrorInfo();
			const { errorInfo } = storeToRefs(storesErrorInfo);
			let msg = errorInfo.value.get(error.request.status);
			if (msg === undefined || msg === null || msg === '') {
				msg = '操作出错，请稍侯再试';
			}
			ElMessage({
				message: error.request.status + '-' + msg,
				type: 'error',
				duration: 3000,
			});
		}
		return Promise.reject(error);
	}
);

interface IResp {
	code: string;
	success: boolean;
	msg: string;
	Records?: any;
	TotalSize?: string;
	RowCnt?: string;
	data?: any;
}
function handleResponse(res: any): IResp {
	// console.log('handleResponse res: ', res);
	if (res.data && isJsonString(res.data)) {
		const data = JSON.parse(res.data);
		// console.log('handleResponse:', data);
		if (data.Records || data.RowCnt) {
			return {
				...data,
				code: res.code,
				success: res.success,
				msg: res.msg,
			};
		} else {
			return {
				data: data,
				code: res.code,
				success: res.success,
				msg: res.msg,
			};
		}
	} else {
		return {
			data: res.data,
			code: res.code,
			success: res.success,
			msg: res.msg,
		};
	}
}

function isJsonString(str: string) {
	if (typeof str === 'string') {
		try {
			var obj = JSON.parse(str);
			if (typeof obj === 'object' && obj) {
				return true;
			} else {
				return false;
			}
		} catch (e) {
			return false;
		}
	}
}

// 导出 axios 实例
export default service;
